package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.constant.RedisConst;
import com.atguigu.spzx.manager.mapper.ProductDetailsMapper;
import com.atguigu.spzx.manager.mapper.ProductMapper;
import com.atguigu.spzx.manager.mapper.ProductSkuMapper;
import com.atguigu.spzx.manager.service.ProductService;
import com.atguigu.spzx.model.dto.product.ProductDto;
import com.atguigu.spzx.model.entity.product.Product;
import com.atguigu.spzx.model.entity.product.ProductDetails;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper ;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;


    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public PageInfo<Product> findByPage(Integer page, Integer limit, ProductDto productDto) {
        PageHelper.startPage(page , limit) ;
        List<Product> productList =  productMapper.findByPage(productDto) ;
        return new PageInfo<>(productList);
    }

    @Override
    public void save(Product product) {
        //1.保存商品信息 Product

        product.setStatus(0); //线上状态：0-初始值，1-上架，-1-自主下架
        product.setAuditStatus(0);
        productMapper.save(product); //主键回填： useGeneratedKeys="true" keyProperty="id"

        Long productId = product.getId();

        //2.保存List<ProductSku> 商品库存单元
        List<ProductSku> productSkuList = product.getProductSkuList();
        for (int i = 0,size = productSkuList.size(); i < size;i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(productId +"_"+ i);
            productSku.setSkuName(product.getName() +" " + productSku.getSkuSpec());
            productSku.setProductId(productId);
            productSku.setSaleNum(0);
            productSku.setStatus(0); //线上状态：0-初始值，1-上架，-1-自主下架
            productSkuMapper.save(productSku);
        }

        //3.保存ProductDetails 商品详情
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(productId);
        productDetails.setImageUrls(product.getDetailsImageUrls());
        productDetailsMapper.save(productDetails);
    }


    @Override
    public Product getById(Long id) {
        //1.查询商品信息
        Product product = productMapper.getById(id);

        //2.根据商品ID查询SKU信息
        List<ProductSku> productSkuList = productSkuMapper.getByProductId(id);
        product.setProductSkuList(productSkuList);

        //3.根据商品ID查询详情信息
        ProductDetails productDetails =  productDetailsMapper.getByProductId(id);
        product.setDetailsImageUrls(productDetails.getImageUrls());
        return product;
    }

    @Override
    public void updateById(Product product) {
        //1.更新商品信息
        productMapper.updateById(product);

        //2.更新SKU信息
        List<ProductSku> productSkuList = product.getProductSkuList();
        for (ProductSku productSku : productSkuList) {
            productSkuMapper.updateById(productSku);
        }

        //3.更新详情信息
        String detailsImageUrls = product.getDetailsImageUrls();
        ProductDetails productDetails = productDetailsMapper.getByProductId(product.getId());
        productDetails.setImageUrls(detailsImageUrls);

        productDetailsMapper.updateById(productDetails);
    }


    @Override
    public void deleteById(Long id) {
        //由于数据库表设计：并没有建立物理的外键约束。所以删除时候，只要把数据都删除即可，无需考虑顺序问题。（按理应先删外键表数据，再删主键表数据）
        //另一个原因：逻辑删除，并没有执行delete语句。而是执行update语句。
        //1.删除商品信息
        productMapper.deleteById(id);

        //2.删除SKU信息
        productSkuMapper.deleteByProductId(id);

        //3.删除详情信息
        productDetailsMapper.deleteByProductId(id);


        //==============================================================================
        // 创建一个新的布隆过滤器
        RBloomFilter<Object> newBloomFilter = redissonClient.getBloomFilter(RedisConst.PRODUCT_NEW_BLOOM_FILTER);
        newBloomFilter.tryInit(1000,0.1); //保存数据的数量，误判率

        // 获取商品skuIdList
        List<Long> skuIdList = productSkuMapper.findSkuIdAll();
        for (Long skuId : skuIdList) {
            newBloomFilter.add(skuId);
        }
        System.out.println("新布隆过滤器中存放的skuIdList.toString() = " + skuIdList.toString());

        //删除旧布隆过滤器，将新的布隆过滤器的名称修改为旧的布隆过滤器的名称。

        // 定义lua脚本
        String script = "if redis.call(\"exists\", KEYS[1]) == 1 then\n"+
                "    redis.call(\"del\" , KEYS[1])\n"+
                "end\n"+
                "if redis.call(\"exists\", \"{\"..KEYS[1]..\"}:config\") == 1 then\n"+
                "    redis.call(\"del\" , \"{\"..KEYS[1]..\"}:config\")\n"+
                "end\n"+
                "if redis.call(\"exists\", KEYS[2]) == 1 then\n"+
                "    redis.call(\"rename\" , KEYS[2] , KEYS[1])\n"+
                "end\n"+
                "if redis.call(\"exists\", \"{\"..KEYS[2]..\"}:config\") == 1 then\n"+
                "    redis.call(\"rename\" , \"{\"..KEYS[2]..\"}:config\" , \"{\"..KEYS[1]..\"}:config\")\n"+
                "end\n"+
                "return 1";
        System.out.println("script = " + script);
        // 执行lua脚本
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script , Long.class) ,
                Arrays.asList(RedisConst.PRODUCT_BLOOM_FILTER , RedisConst.PRODUCT_NEW_BLOOM_FILTER)) ;

        // 打印日志
        log.info("reset bloomFilter成功了............result= "+result);


    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if(auditStatus == 1){
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        }else{
            product.setAuditStatus(-1);
            product.setAuditMessage("审批驳回");
        }

        productMapper.updateById(product);
    }


    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if(status==1){
            product.setStatus(1);
        }else{
            product.setStatus(-1);
        }
        productMapper.updateById(product);

        //更新商品状态的时候，对应SKU数据状态也要更新。
        productSkuMapper.updateStatusByProductId(id,product.getStatus());

        if(status == 1){  //上架商品，初始化布隆过滤器
            //把商品放置在布隆过滤器中
            List<Long> productSkuIdList = productSkuMapper.getProdudctSkuIdListByProductId(id);
            for (Long productSkuId : productSkuIdList) {
                RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.PRODUCT_BLOOM_FILTER);
                bloomFilter.add(productSkuId); // 假设，通过3个hash()函数计算二进制位索引，把0标记成1.
            }
        }

    }
}